﻿using Entity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using XingWeiDaWMSProject.IService;

namespace XingWeiDaWMSProject.Controllers
{
    public class UserController : Controller
    {
        private readonly ISysOrgUserManagementService _userService;
        private readonly ILogger<UserController> _logger;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public UserController(
            ISysOrgUserManagementService userService,
            ILogger<UserController> logger,
            IWebHostEnvironment webHostEnvironment)
        {
            _userService = userService;
            _logger = logger;
            _webHostEnvironment = webHostEnvironment;
        }

        // 个人资料页面
        public async Task<IActionResult> Profile()
        {
            try
            {
                string currentAccount = _userService.GetCurrentUserAccount();
                if (string.IsNullOrEmpty(currentAccount))
                {
                    TempData["Error"] = "请先登录系统";
                    return RedirectToAction("Login", "Login");
                }

                var user = await _userService.GetUserByAccountAsync(currentAccount);
                if (user == null)
                {
                    TempData["Error"] = "用户不存在或已被禁用";
                    return RedirectToAction("Login", "Login");
                }

                return View(user);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载个人资料失败");
                TempData["Error"] = "系统异常，请稍后重试";
                return RedirectToAction("Index", "Home");
            }
        }

        // 保存个人资料（含头像上传）
        [HttpPost]
        public async Task<IActionResult> SaveProfile(SysOrgUserManagement user, IFormFile avatarFile)
        {
            try
            {
                string currentAccount = _userService.GetCurrentUserAccount();
                if (string.IsNullOrEmpty(currentAccount))
                {
                    TempData["Error"] = "请先登录系统";
                    return RedirectToAction("Login", "Login");
                }

                // 验证必要字段
                if (string.IsNullOrEmpty(user.UserName))
                {
                    TempData["Error"] = "用户姓名不能为空";
                    return RedirectToAction("Profile");
                }

                var existingUser = await _userService.GetUserByAccountAsync(currentAccount);
                if (existingUser == null)
                {
                    TempData["Error"] = "用户不存在";
                    return RedirectToAction("Profile");
                }

                // 1. 更新基本资料
                existingUser.UserName = user.UserName?.Trim();
                existingUser.Sex = user.Sex;
                existingUser.PhoneNumber = user.PhoneNumber?.Trim();
                existingUser.UpdateBy = currentAccount;
                existingUser.UpdateTime = DateTime.Now;

                // 2. 处理头像上传（保持原逻辑，优化路径判断）
                if (avatarFile != null && avatarFile.Length > 0)
                {
                    // 大小限制：≤2MB
                    if (avatarFile.Length > 2 * 1024 * 1024)
                    {
                        TempData["Error"] = "头像文件大小不能超过2MB";
                        return RedirectToAction("Profile");
                    }
                    // 格式限制：jpg/jpeg/png/gif
                    var allowedExts = new[] { ".jpg", ".jpeg", ".png", ".gif" };
                    var fileExt = Path.GetExtension(avatarFile.FileName).ToLower();
                    if (!allowedExts.Contains(fileExt))
                    {
                        TempData["Error"] = "头像只支持jpg、jpeg、png、gif格式";
                        return RedirectToAction("Profile");
                    }
                    // 保存路径（确保wwwroot存在）
                    var webRoot = _webHostEnvironment.WebRootPath ?? Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
                    var saveDir = Path.Combine(webRoot, "uploads", "avatars");
                    if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
                    var fileName = $"{Guid.NewGuid()}{fileExt}";
                    var filePath = Path.Combine(saveDir, fileName);
                    await using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await avatarFile.CopyToAsync(stream);
                    }
                    // 更新头像路径（相对路径）
                    existingUser.UserAvatar = $"/uploads/avatars/{fileName}";
                }

                // 3. 最终更新数据库
                bool isSuccess = await _userService.UpdateUserAsync(existingUser);
                if (isSuccess)
                {
                    TempData["Message"] = "资料更新成功";
                    _logger.LogInformation("用户 {Account} 更新个人资料成功", currentAccount);
                }
                else
                {
                    TempData["Error"] = "资料更新失败，请稍后重试";
                    _logger.LogWarning("用户 {Account} 更新个人资料失败", currentAccount);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存个人资料失败");
                TempData["Error"] = "保存失败，请稍后重试";
            }

            return RedirectToAction("Profile");
        }

        // 修改密码（适配服务层返回值，精准提示）
        [HttpPost]
        public async Task<IActionResult> DoChangePassword(string oldPassword, string newPassword, string confirmNewPassword)
        {
            // 1. 前端二次校验（新密码一致性）
            if (newPassword != confirmNewPassword)
            {
                TempData["Error"] = "新密码与确认密码不一致";
                return RedirectToAction("Profile");
            }

            string currentAccount = _userService.GetCurrentUserAccount();
            try
            {
                // 2. 调用服务层修改密码（获取具体结果）
                string result = await _userService.ChangePasswordAsync(currentAccount, oldPassword, newPassword);
                if (result == "success")
                {
                    TempData["Message"] = "密码修改成功，请重新登录";
                    // 可选：修改成功后清除Session，强制重新登录
                    HttpContext.Session.Remove("LoginUserName");
                }
                else
                {
                    TempData["Error"] = result;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改密码控制器异常（账号：{Account}）", currentAccount);
                TempData["Error"] = "修改失败，请稍后重试";
            }

            return RedirectToAction("Profile");
        }
    }
}